/**
 * 密码存储工具模块
 * 提供安全的密码保存和读取功能
 */

// localStorage键名常量
export const STORAGE_KEYS = {
  REMEMBER: 'rememberPassword',
  USERNAME: 'rememberedUsername', 
  PASSWORD: 'rememberedPassword'
} as const

/**
 * 简单的加密函数（基于Base64和简单的字符串变换）
 * 注意：这只是一个基础的混淆方法，不是真正的加密
 * 在生产环境中建议使用更安全的加密库
 */
const simpleEncrypt = (text: string): string => {
  try {
    // 将字符串反转并进行Base64编码
    const reversed = text.split('').reverse().join('')
    return btoa(reversed + '|' + Date.now().toString(36))
  } catch (error) {
    console.error('加密失败:', error)
    return btoa(text)
  }
}

/**
 * 简单的解密函数
 */
const simpleDecrypt = (encrypted: string): string => {
  try {
    const decoded = atob(encrypted)
    const parts = decoded.split('|')
    if (parts.length >= 2) {
      // 取出原始内容并反转
      return parts[0].split('').reverse().join('')
    }
    // 如果格式不对，尝试直接base64解码（向后兼容）
    return atob(encrypted)
  } catch (error) {
    console.error('解密失败:', error)
    return ''
  }
}

/**
 * 保存记住的登录凭据
 */
export const saveRememberedCredentials = (username: string, password: string, remember: boolean): void => {
  try {
    if (remember) {
      localStorage.setItem(STORAGE_KEYS.REMEMBER, 'true')
      localStorage.setItem(STORAGE_KEYS.USERNAME, username)
      localStorage.setItem(STORAGE_KEYS.PASSWORD, simpleEncrypt(password))
      console.log('登录凭据已保存')
    } else {
      clearRememberedCredentials()
    }
  } catch (error) {
    console.error('保存登录凭据失败:', error)
  }
}

/**
 * 加载记住的登录凭据
 */
export const loadRememberedCredentials = (): { username: string; password: string; remember: boolean } => {
  const defaultCredentials = { username: '', password: '', remember: false }
  
  try {
    const remembered = localStorage.getItem(STORAGE_KEYS.REMEMBER)
    if (remembered === 'true') {
      const username = localStorage.getItem(STORAGE_KEYS.USERNAME) || ''
      const encryptedPassword = localStorage.getItem(STORAGE_KEYS.PASSWORD) || ''
      const password = encryptedPassword ? simpleDecrypt(encryptedPassword) : ''
      
      return {
        username,
        password,
        remember: true
      }
    }
  } catch (error) {
    console.error('加载记住的登录凭据失败:', error)
    // 如果加载失败，清除可能损坏的数据
    clearRememberedCredentials()
  }
  
  return defaultCredentials
}

/**
 * 清除记住的登录凭据
 */
export const clearRememberedCredentials = (): void => {
  try {
    localStorage.removeItem(STORAGE_KEYS.REMEMBER)
    localStorage.removeItem(STORAGE_KEYS.USERNAME)
    localStorage.removeItem(STORAGE_KEYS.PASSWORD)
    console.log('已清除保存的登录凭据')
  } catch (error) {
    console.error('清除登录凭据失败:', error)
  }
}

/**
 * 检查是否启用了记住密码功能
 */
export const isRememberEnabled = (): boolean => {
  try {
    return localStorage.getItem(STORAGE_KEYS.REMEMBER) === 'true'
  } catch (error) {
    console.error('检查记住密码状态失败:', error)
    return false
  }
}